<template>
	<div class="pt15 pr15 pb15 pl15">
		<el-form ref="lineFormRef" :model="line" size="small" label-width="50px">
			<el-form-item label="来往">
				<el-input v-model="line.contact" placeholder="来往" clearable readonly></el-input>
			</el-form-item>
			<el-form-item label="类型">
				<el-input v-model="line.type" placeholder="类型" clearable readonly></el-input>
			</el-form-item>
			<el-form-item label="名称">
				<el-input v-model="line.label" placeholder="请输入名称" clearable></el-input>
			</el-form-item>
			<el-form-item label="条件">
				<el-input v-model="line.expression" placeholder="请输入条件表达式值必须等于true或false，支持EL表达式，例如: ${data.status != 200}" clearable></el-input>
			</el-form-item>
			<el-form-item v-if="readonly == false">
				<el-button @click="onLineChange" type="primary" :loading="loading.extend" icon="el-icon-check" size="small">
					保存
				</el-button>
			</el-form-item>
		</el-form>
	</div>
</template>

<script lang="ts">
import { defineComponent, reactive, toRefs, ref } from 'vue';
import { ElMessage } from 'element-plus';
import { useRoute } from 'vue-router';
import { addWorkableLine, editWorkableLine, getWorkableLine } from '/@/api/workable/line/index';

// 定义接口来定义对象的类型
interface WorkflowDrawerLineState {
	line: any;
}

export default defineComponent({
	name: 'workable/editor/drawer/line',
	props: {
		readonly: {
			type: Boolean,
		},
	},
	setup(props, { emit }) {
		const route = useRoute();
		const lineFormRef = ref();
		const state = reactive<WorkflowDrawerLineState>({
			line: {},
			loading: {
				extend: false,
			},
			readonly: false,
		});
		// 获取父组件数据
		const getParentData = (data: object) => {
			state.line = data;
			state.readonly = props.readonly;
			getWorkableLine(state.line).then(res => {
				if(res.code == 0){
					if(res.data && res.data.id){
						state.line.id = res.data.id;
					}
				}
			});
		};
		// 保存
		const onLineChange = () => {
			lineFormRef.value.validate((valid: boolean) => {
				if (valid) {
					state.loading.extend = true;
					if(state.line.id){
						editWorkableLine(state.line).then(res => {
							if(res.code == 0){
								state.loading.extend = false;
								ElMessage.success('保存成功');
								state.line = res.data;
								emit('change', state.line);
								emit('close');
							}
						})
					}else{
						addWorkableLine(state.line).then(res => {
							if(res.code == 0){
								state.loading.extend = false;
								ElMessage.success('保存成功');
								state.line = res.data;
								emit('change', state.line);
								emit('close');
							}
						})
					}
				} else {
					return false;
				}
			});
		};
		return {
			lineFormRef,
			getParentData,
			onLineChange,
			...toRefs(state),
		};
	},
});
</script>
